package com.efounder.widget;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import androidx.fragment.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.activity.TabBottomActivity;
import com.efounder.broadcast.BroadCastutil;
import com.efounder.fragment.MenuFragment;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AbFragmentManager;

import com.efounder.utils.FilesOperationDataUtil;
import com.pansoft.resmanager.ResFileManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/*import com.core.xml.StubObject;
import com.efounder.R;
import com.efounder.activity.MainActivity;
import com.efounder.broadcast.BroadCastutil;
import com.efounder.fragment.SimpleWebFragment;
import com.efounder.util.FilesOperationDataUtil;
import com.efounder.util.FragmentUtil;*/


public class CommonGridViewWithLastSelfDefine extends GridView {


    private static final int GRIDVIEW_COUNT = 4;// 声明每一页皮肤的个数

    private final Context context;// 上下文
    public ArrayList<Object> viewList = new ArrayList<Object>();// Activity传来的数据源
    List<View> animationList = new ArrayList<View>();
    List<RelativeLayout> delList = new ArrayList<RelativeLayout>();
    ArrayList<Object> slideList;//文件里的list
    ArrayList<Object> bottomList;//需要显示的list
    //此view的广播
    viewPagewithGridViewBroadcast viewPagewithGridViewBroadcast;

    private List<View> allViews = new ArrayList<View>();

    bottomGridAdapter adapter;
    private String localfilename;

    private boolean isAnim =false;
    public CommonGridViewWithLastSelfDefine(Context context, AttributeSet attrs,String localfilename) {
        super(context, attrs);
        this.context = context;
        this.localfilename = localfilename;
        this.setNumColumns(GRIDVIEW_COUNT);
        //this.setFocusable(true);
        //this.requestFocus();
        // 注册intentFilter
        viewPagewithGridViewBroadcast = new viewPagewithGridViewBroadcast();
        // 注册intentFilter
        IntentFilter filter = new IntentFilter();
        filter.addAction("CommonGridViewuiChange");
        BroadCastutil.getinstance().addbroadCast(viewPagewithGridViewBroadcast);
        // 注册filter，连接broadcastSaveFile
        context.registerReceiver(viewPagewithGridViewBroadcast, filter);
        slideList = FilesOperationDataUtil.readFile(context,localfilename);
        resetData();
    }
    /*
     * 刷新组件
     */
    public void refresh(){
        bottomList = new ArrayList<Object>();
        slideList= FilesOperationDataUtil.readFile(context,localfilename);
        for(int i=0;i<slideList.size();i++){
            @SuppressWarnings("unchecked")

            StubObject map = (StubObject) slideList.get(i);
            if((Boolean)(map.getBoolean("ischecked", false))==true){
                bottomList.add(map);
            }
        }

        viewList= new ArrayList<Object>();

        for(int k = 0 ;k<bottomList.size();k++){
            viewList.add(k,bottomList.get(k));
        }
	/*	HashMap<String, Object> mapgrid0 = new HashMap<String, Object>();
		mapgrid0.put("images", "addapp");
		mapgrid0.put("title", "自定义");
		viewList.add(mapgrid0);*/
        StubObject mapgrid0  = new StubObject();
        mapgrid0.setString("normalIcon", "addapp");
        mapgrid0.setString("caption", "自定义");
        viewList.add(mapgrid0);
        this.update();
    }


    // 为每个单元设置数据
    private class bottomGridAdapter extends BaseAdapter {

        private Context mContext;
        private LayoutInflater skinInflater;

        private bottomGridAdapter(Context context) {
            this.mContext = context;
            skinInflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {

            int size = (viewList == null ? 0 : viewList.size());
            return size;
        }

        @Override
        public Object getItem(int position) {
            return viewList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // 这里本来return的是position
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final int nowPosition =  position;
            ViewHolder holder;
            if (convertView != null) {
                holder = (ViewHolder) convertView.getTag();
            } else {
                // 加载布局生成布局对象，然后取得布局中的控件，为控件设置内容
                convertView = skinInflater.inflate(R.layout.viewpager_bottomgrid_item,
                        null);
                holder = new ViewHolder();
                holder.name = (TextView) convertView
                        .findViewById(R.id.skin_popup_app_name);
                holder.icon = (ImageView) convertView
                        .findViewById(R.id.skin_popup_app_icon);
                //holder.icon.requestFocus();
                holder.layout = (RelativeLayout) convertView
                        .findViewById(R.id.item_Rel);
				/*holder.icon.setBackgroundResource((Integer) viewList.get(
						nowPosition).get("images"));*/
				/*Log.i("###############", (String) viewList.get(nowPosition).get(
						"title")+"...");*/
				/*if(nowPosition ==viewList.size()-1){
					holder.icon.setBackgroundResource((Integer) viewList.get(
							nowPosition).get("images"));
				}else{*/
                //Bitmap bm =BitmapFactory.decodeFile((String)(viewList.get(nowPosition).get("images")+""));
					/*ApplicationInfo appInfo = context.getApplicationInfo();
		        	int ID = context.getResources().getIdentifier(String.valueOf(viewList.get(nowPosition).get("images")), "drawable", appInfo.packageName);
		        	Bitmap bm = BitmapFactory.decodeResource(context.getResources(), ID);*/

                convertView.setTag(holder);
            }
            ApplicationInfo appInfo = context.getApplicationInfo();
            //int ID = context.getResources().getIdentifier((String) listmap.get(position).get("images"), "drawable", appInfo.packageName);
            //Bitmap bm = BitmapFactory.decodeResource(context.getResources(), ID);
            String menuIcon=(String) ((StubObject)viewList.get(nowPosition)).getString("normalIcon", "");
            menuIcon = ResFileManager.IMAGE_DIR + "/" + menuIcon;
            Bitmap bm = null;
            if(position == viewList.size()-1){
                int ID = context.getResources().getIdentifier(String.valueOf( ((StubObject)viewList.get(nowPosition)).getString("normalIcon", "")), "drawable", appInfo.packageName);
                bm = BitmapFactory.decodeResource(context.getResources(), ID);
            }else{

                //menuIcon = ResFileManager.IMAGE_DIR + "/" + menuIcon;
//			normalIcon = ResFileManager.IMAGE_DIR  + normalIcon;
                File file = new File(menuIcon);

                if (file.exists()) {
                    bm = BitmapFactory.decodeFile(menuIcon);
                    //bitmapList.add(bm);
                }
            }
            if(bm==null){
                int resID = context.getResources().getIdentifier("iframe_icon_refresh", "drawable", appInfo.packageName);
                bm = BitmapFactory.decodeResource(context.getResources(), resID);
            }
            holder.icon.setImageBitmap(bm);
			/*holder.icon.setBackgroundResource((Integer) viewList.get(
					nowPosition).get("images"));*/
            //}
            holder.name.setText((String)  ((StubObject)viewList.get(nowPosition)).getString("caption",""));

            holder.del = (ImageView) convertView.findViewById(R.id.cross_icon);
            holder.del.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    String text = (String)  ((StubObject)viewList.get(nowPosition)).getString("caption", "");

                    for (int i = 0; i < slideList.size(); i++) {
                        @SuppressWarnings("unchecked")
                        StubObject map = (StubObject) slideList.get(i);
                        if (map.getString("caption","").equals(text)) {
                            //map.remove("ischecked");

                            map.setBoolean("ischecked", false);
                            break;
                        }

                    }
                    FilesOperationDataUtil.clearFileData(context,localfilename);
                    FilesOperationDataUtil.createFile(context, slideList,localfilename);
                    //-1代表点击删除键发送的广播
                    //sendBroadCast(-1);

                    viewList.remove(nowPosition);
                    update();
                    cleanAnim();
                }
            });

            // 设置标题和监听
            //holder.layout.setTag(nowPosition);// 为onClick方法提供id
            // holder.layout.setOnClickListener(ViewPagerView.this);
            //holder.layout.setAlpha(50);
            return convertView;
        }
    }

    // 定义一个类，包含需要的每个布局和控件
    static class ViewHolder {
        RelativeLayout layout;
        ImageView icon;
        TextView name;
        ImageView del;
    }


    // 接收来自Activity的list列表
    public void setArrayList(ArrayList<Object> list) {
        this.viewList = list;
        // 为ViewPager设置Adapter
        adapter = new bottomGridAdapter(context);
        this.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    public void update() {
        //resetData();
        adapter.notifyDataSetChanged();
    }

    public void resetData() {
        allViews.clear();

        // 加载每一个ViewPager页的view
        LayoutInflater inflater = LayoutInflater.from(context);
		/*View mView = inflater.inflate(R.layout.appmenu_gridview, null);
			LinearLayout grid_container = (LinearLayout) mView.findViewById(R.id.grid_container);
			final GridView skinGridView = (GridView) mView
					.findViewById(R.id.menu_bottom_gridview);*/

        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        this.setColumnWidth(width/5);

			/*skinGridView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(isAnim)
					cleanAnim();
				}
			});*/
        this.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if(isAnim){
                    cleanAnim();
                    return ;
                }
                // TODO Auto-generated method stub
                if ( position == viewList.size()-1) {
                    //0代表点击第一个按钮是发送的广播标记。
						/*Intent intent = new Intent();
						intent.setClass(context, MenuActivity.class);
						context.startActivity(intent);*/
                    MenuFragment menuFrag = new MenuFragment();
                    TabBottomActivity tabActivity = TabBottomActivity.getInstance();
                    tabActivity.jumpAndStoreStack(menuFrag);


                }
                if ( position != viewList.size()-1) {
                    //Fragment	frag = com.efounder.util.AbFragmentManager.getFragment(viewList.get(position));
                    AbFragmentManager ab = new AbFragmentManager(context);

                    Fragment frag = ab.getFragment( ((StubObject)viewList.get(position)));
                    TabBottomActivity tabActivity = TabBottomActivity.getInstance();
                    tabActivity.jumpAndStoreStack(frag);
                    //StubObject urlWithparam = new StubObject();
					/*String url;
					Intent intent = new Intent();
					url = (String) viewList.get( position).getString("url","");
					intent.putExtra("url", url);
					String title = (String) viewList.get( position).getString("caption","");
					intent.putExtra("title", title);
					intent.setClass(context, SimpleWebFragment_url.class);
					context.startActivity(intent);*/
                    //url = (String) viewList.get((k1) * GRIDVIEW_COUNT + position).get("url");
                    //	urlWithparam.setString(CAPTION,  (String) viewList.get((k1) * GRIDVIEW_COUNT + position).get("title"));
                    //urlWithparam.setString("url", url);
					/*SimpleWebFragment webFragment = new SimpleWebFragment(urlWithparam);
					 FragmentUtil.init((MainActivity)context);
					 if(webFragment!=null){
			        // FragmentUtil.puttoStack(webFragment,true);
						 itemClick.itemClick(webFragment);
					 }*/
                }
                // showTab(position); // 显示目标tab
                //ft.commit();
                //showFragment(fragToShow);


					/*for(int j=0 ;j<animationList.size();j++){
						animationList.get(j).clearAnimation();
						delList.get(j).setVisibility(View.INVISIBLE);
					}*/

            }
        });
        this.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0,
                                           View arg1, int arg2, long arg3) {
                if(isAnim){
                    cleanAnim();
                    return true ;
                }
                isAnim = true;
                // TODO Auto-generated method stub
					/*CommonGridView.this.setFocusable(true);
					CommonGridView.this.setFocusableInTouchMode(true);
					CommonGridView.this.requestFocus();*/
                //skinGridView.requestFocus();
                int nCount = CommonGridViewWithLastSelfDefine.this.getChildCount();
                CommonGridViewWithLastSelfDefine.this.setSelector(new ColorDrawable(Color.TRANSPARENT));
				/*	for(int i = 0 ;i < nCount-1; i ++){
						View v = CommonGridView.this.getChildAt(i);
						RelativeLayout layout;
						Animation shake;
						if(i % 2 == 0){
							shake = AnimationUtils.loadAnimation(
								context, R.anim.icon_anim_left);
							shake.reset();
							shake.setFillAfter(true);
						}
						else{
							shake = AnimationUtils.loadAnimation(
									context, R.anim.icon_anim_right);
								shake.reset();
								shake.setFillAfter(true);
						}
						v.startAnimation(shake);
						animationList.add(v);
						layout = (RelativeLayout)v.findViewById(R.id.view_delete);
						delList.add(layout);

						layout.setVisibility(View.VISIBLE);
					}
					}else{*/
                for(int i = 0 ;i < nCount-1; i ++){
                    View v = CommonGridViewWithLastSelfDefine.this.getChildAt(i);
                    RelativeLayout layout;
                    Animation shake;
                    if(i % 2 == 0){
                        shake = AnimationUtils.loadAnimation(
                                context, R.anim.icon_anim_left);
                        shake.reset();
                        shake.setFillAfter(true);
                    }
                    else{
                        shake = AnimationUtils.loadAnimation(
                                context, R.anim.icon_anim_right);
                        shake.reset();
                        shake.setFillAfter(true);
                    }
                    v.startAnimation(shake);
                    animationList.add(v);
                    layout = (RelativeLayout)v.findViewById(R.id.view_delete);
                    delList.add(layout);
                    layout.setVisibility(View.VISIBLE);
                }
                return true;
            }
        });

			/*this.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View arg0, boolean arg1) {
					// TODO Auto-generated method stub


					if(arg1){
						Log.i("viewpagewithgrid有焦点", "有焦点");
					}else{

						cleanAnim();
					}
				}
			});*/

        bottomGridAdapter adapter = new bottomGridAdapter(context);
        this.setAdapter(adapter);

        adapter.notifyDataSetChanged();
        allViews.add(this);
    }
    private void cleanAnim(){
        isAnim =false;
        for(int j=0 ;j<animationList.size();j++){
            animationList.get(j).clearAnimation();
            delList.get(j).setVisibility(View.INVISIBLE);
        }
    }
    /*
     * 文件保存成功后发送广播
     */
    public void sendBroadCast(int i) {

        String ACTION = "uiChange";
        Intent intent = new Intent();
        if(i==0){
            intent.putExtra("name", "button0");
        }else if(i==1){
            intent.putExtra("name", "button0-");
        }
        else{
            intent.putExtra("name", "del");
        }
        intent.setAction(ACTION);
        // 普通广播
        context.sendBroadcast(intent);
    }

    public class viewPagewithGridViewBroadcast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            String name = intent.getStringExtra("name");
            if("buttonclick".equals(name)){
                refresh();
            }

        }
    }
    @Override



    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {



        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,



                MeasureSpec.AT_MOST);



        super.onMeasure(widthMeasureSpec, expandSpec);



    }

}
